#include"../muduo/include/muduo/net/TcpServer.h"
#include "../muduo/include/muduo/net/EventLoop.h"
#include "../muduo/include/muduo/net/TcpConnection.h"
#include "../muduo/include/muduo/net/Buffer.h"

#include <iostream>
#include <string>
#include <unordered_map>

// using namespace std;
class DictServer
{
    public:
    DictServer(int port):_server(&_baseloop,
        muduo::net::InetAddress("0.0.0.0",port),
        "DictServer",muduo::net::TcpServer::kReusePort)
    {
        //设置连接事件
        _server.setConnectionCallback(std::bind(&DictServer::OnConnection,this,std::placeholders::_1));
        //设置连接消息回调
        _server.setMessageCallback(std::bind(&DictServer::OnMessage,this,
            std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    void Start()
    {
        _server.start();//开始监听
        _baseloop.loop();//开始死循环事件监控
    }
    private:
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout<<"连接成功！"<<std::endl;
        }
        else
        {
            std::cout<<"连接断开！"<<std::endl;
        }
    }
    void OnMessage(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buffer,muduo::Timestamp)
    {
        //创建字典
        static std::unordered_map<std::string,std::string> dict={{"hello","你好"},{"shuai","帅"},{"world","世界"}};
        std::string msg=buffer->retrieveAllAsString();
        std::string res;
        auto it=dict.find(msg);
        if(it==dict.end())
        {
            res="未知单词";
        }
        else{
            res=it->second;
        }
        conn->send(res);
    }
    private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer dictsvr(8080);
    dictsvr.Start();
    return 0;
}